import apiClient from './config'
import type { 
  Permission, 
  CreatePermissionRequest, 
  UpdatePermissionRequest, 
  PermissionListParams,
  ApiResponse 
} from './types'

export const permissionsApi = {
  // 获取权限列表（树形结构）
  getPermissions: (params?: PermissionListParams): Promise<ApiResponse<Permission[]>> => {
    return apiClient.get('/permissions', { params })
  },

  // 获取所有权限（扁平结构）
  getAllPermissions: (): Promise<ApiResponse<Permission[]>> => {
    return apiClient.get('/permissions/all')
  },

  // 获取权限详情
  getPermission: (id: number): Promise<ApiResponse<Permission>> => {
    return apiClient.get(`/permissions/${id}`)
  },

  // 创建权限
  createPermission: (data: CreatePermissionRequest): Promise<ApiResponse<Permission>> => {
    return apiClient.post('/permissions', data)
  },

  // 更新权限
  updatePermission: (data: UpdatePermissionRequest): Promise<ApiResponse<Permission>> => {
    return apiClient.put(`/permissions/${data.id}`, data)
  },

  // 删除权限
  deletePermission: (id: number): Promise<ApiResponse<any>> => {
    return apiClient.delete(`/permissions/${id}`)
  },

  // 批量删除权限
  batchDeletePermissions: (ids: number[]): Promise<ApiResponse<any>> => {
    return apiClient.delete('/permissions/batch', { data: { ids } })
  },

  // 更新权限状态
  updatePermissionStatus: (id: number, status: 'active' | 'inactive'): Promise<ApiResponse<any>> => {
    return apiClient.patch(`/permissions/${id}/status`, { status })
  },

  // 获取父级权限列表
  getParentPermissions: (type?: string): Promise<ApiResponse<Permission[]>> => {
    return apiClient.get('/permissions/parents', { params: { type } })
  },

  // 移动权限（调整父子关系）
  movePermission: (id: number, parentId?: number): Promise<ApiResponse<any>> => {
    return apiClient.patch(`/permissions/${id}/move`, { parentId })
  },

  // 同步权限（从代码中同步）
  syncPermissions: (): Promise<ApiResponse<{ added: number; updated: number; removed: number }>> => {
    return apiClient.post('/permissions/sync')
  },

  // 检查权限代码是否可用
  checkPermissionCode: (code: string, excludeId?: number): Promise<ApiResponse<{ available: boolean }>> => {
    return apiClient.get('/permissions/check-code', { 
      params: { code, excludeId } 
    })
  },

  // 获取权限树（用于选择器）
  getPermissionTree: (includeButtons?: boolean): Promise<ApiResponse<Permission[]>> => {
    return apiClient.get('/permissions/tree', { 
      params: { includeButtons } 
    })
  },

  // 导出权限配置
  exportPermissions: (): Promise<Blob> => {
    return apiClient.get('/permissions/export', {
      responseType: 'blob'
    })
  },

  // 导入权限配置
  importPermissions: (file: File): Promise<ApiResponse<any>> => {
    const formData = new FormData()
    formData.append('file', file)
    return apiClient.post('/permissions/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}